import type { AutoFixResult } from "../../types/autoFix";

const API_URL = "/api/auto-fix";

export async function runAutoFix(files: File[], targetIssue?: { file: string; line?: number; message?: string }): Promise<AutoFixResult> {
  const form = new FormData();
  files.forEach((f) => form.append("files", f, f.name));
  if (targetIssue) {
    form.append("target_issue", JSON.stringify(targetIssue));
  }
  // Attach selected provider and OpenAI key (if any) from localStorage
  try {
    const provider = window.localStorage.getItem("ai_agent_llm_provider");
    const openaiKey = window.localStorage.getItem("ai_agent_openai_key");
    if (provider) form.append("provider", provider);
    if (provider === "openai" && openaiKey) form.append("openai_key", openaiKey);
  } catch (e) {
    // ignore storage errors
  }
  const res = await fetch(API_URL, { method: "POST", body: form });
  const data = (await res.json()) as AutoFixResult;
  if (!res.ok) {
    return {
      success: false,
      error: data?.error || "自动修复接口失败",
    };
  }
  return data;
}

export async function sendChat(files: File[], userMessage: string, targetIssue?: { file: string; line?: number; message?: string }): Promise<AutoFixResult> {
  const form = new FormData();
  files.forEach((f) => form.append("files", f, f.name));
  form.append("user_message", userMessage);
  if (targetIssue) {
    form.append("target_issue", JSON.stringify(targetIssue));
  }
  // Attach selected provider and OpenAI key (if any) from localStorage
  try {
    const provider = window.localStorage.getItem("ai_agent_llm_provider");
    const openaiKey = window.localStorage.getItem("ai_agent_openai_key");
    if (provider) form.append("provider", provider);
    if (provider === "openai" && openaiKey) form.append("openai_key", openaiKey);
  } catch (e) {
    // ignore storage errors
  }
  const res = await fetch(API_URL, { method: "POST", body: form });
  const data = (await res.json()) as AutoFixResult;
  if (!res.ok) {
    return {
      success: false,
      error: data?.error || "聊天接口失败",
    };
  }
  return data;
}
